import 'dart:io';

import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/log_record/student.dart';

/**
 * 
 * @Description TODO
 * @Author liuer
 * @CreateTime 2023年11月21日 19:35
 */
class DBManager {
  /// 数据库名
  final String _dbName = "logRecord.db";

  /// 数据库版本
  final int _version = 1;

  static final DBManager _instance = DBManager._();

  factory DBManager() {
    return _instance;
  }

  DBManager._();

  static Database? _db;

  Future<Database> get db async {
    // if (_db != null) {
    //   return _db;
    // }
    // _db = await _initDB();
    // return _db;
    return _db ??= await _initDB();
  }

  /// 初始化数据库
  Future<Database> _initDB() async {
    Directory directory = await getApplicationDocumentsDirectory();
    String path = join(directory.path, _dbName);
    return await openDatabase(
      path,
      version: _version,
      onCreate: _onCreate,
      onUpgrade: _onUpgrade,
    );
  }

  /// 创建表
  Future _onCreate(Database db, int version) async {
    const String sql = """
    CREATE TABLE ErrorLog(
      id INTEGER primary key AUTOINCREMENT,
      logType TEXT,
      logLevel INTEGER,
      isUpload BOOL,
      mobileName TEXT,
      systemVersion TEXT,
      appVersion TEXT,
      systemType TEXT,
      errorType TEXT,
      errorString TEXT,
      currentRoute TEXT,
      timeDate TEXT,
      timeStamp INTEGER
    )
    """;
    return await db.execute(sql);
  }

  /// 更新表
  Future _onUpgrade(Database db, int oldVersion, int newVersion) async {}
  /// 保存数据
  Future saveData(Map<String,dynamic> errorMap) async {
    Database database = await db;
    return await database.insert("ErrorLog", errorMap);
  }

  /// 使用SQL保存数据
  Future saveDataBySQL(Student student) async {
    const String sql = """
    INSERT INTO Student(name,age,sex) values(?,?,?)
    """;
    Database database = await db;
    return await database.rawInsert(sql, [student.name, student.age, student.sex]);
  }

  /// 查询全部数据
  Future<List<dynamic>?> findAll() async {
    Database? database = await db;
    List<Map<String, Object?>> result = await database.query("ErrorLog");
    if (result.isNotEmpty) {
      return result;
    } else {
      return [];
    }
  }

  ///条件查询
  Future<List<Student>?> find(int sex) async {
    Database database = await db;
    List<Map<String, Object?>> result =
    await database.query("Student", where: "sex=?", whereArgs: [sex]);
    if (result.isNotEmpty) {
      return result.map((e) => Student.fromJson(e)).toList();
    } else {
      return [];
    }
  }

  /// 修改
  Future<int> update(Map<String,dynamic> errorMap) async {
    Database database = await db;
    int count =
    await database.update("ErrorLog", errorMap, where: "timeStamp=?", whereArgs: [errorMap['timeStamp']]);
    return count;
  }

  /// 删除
  Future<int> delete(int id) async {
    Database database = await db;
    int count = await database.delete("ErrorLog", where: "id=?", whereArgs: [id]);
    return count;
  }

  /// 删除全部
  Future<int> deleteAll() async {
    Database database = await db;
    int count = await database.delete("ErrorLog");
    return count;
  }

}
